<?php
require_once '../app/Mage.php';
require_once '../lib/Varien/Io/File.php';
set_time_limit(0);
ini_set('memory_limit','2048M');
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
define('TEMP_TABLE','temp_additionaldata');
define('FRESH_INSTALL',false);


function p($ar,$ex=1)
{
	echo "<pre>";
	print_r($ar);
	if($ex==1) exit;
}
function m($obj,$ex=1)
{
	echo "<pre>";
	print_r(get_class($obj));
	print_r(get_class_methods(get_class($obj)));
	if($ex==1) exit;
}

class updateAdditionalData
{
	protected $_addtionalFiles;
	protected $_batchLimit = 50;
	protected $_destinationPath;
	public $logFile = 'addtionalData.log';
	public $logMsg = array();
    public $zipArray = array();
	public $fileArray = array();
    public $prod_attribs=array();
	public $sql;
	public $connect;
	public $total;
	public $start;
	public $entityTypeId;
    public $con;
	protected $_store;
    public $file;
	


	public function __construct()
	{
		$this->_addtionalFiles = $this->getConfigVal('additional_file');
       	$this->con = Mage::getSingleton('core/resource')->getConnection('core_write');
       	$this->dbConnectNormal($this->con->getConfig());
       	$this->entityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
		//$this->_store = Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
        $this->_store = Mage::app()->getStore()->getId();
        //Clean log file
		if(file_exists(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile)) {
			//unlink(Mage::getBaseDir('var').DS.'log'.DS.$this->logFile);
		}
        $this->init();
		
	}
    public function getConfigVal($field)
	{
		return Mage::getStoreConfig('managecatalogspr/price_file/'.$field);
	}
	public function closeConnection()
	{
		mysql_close($this->connect);
		unset($this);
	}
	public function init()
    {
        $installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
		$this->prod_attribs['tour'] = $installer->getAttribute('catalog_product', "tour");
		$this->prod_attribs['brochure'] = $installer->getAttribute('catalog_product', "brochure");
        $this->prod_attribs['rebate'] = $installer->getAttribute('catalog_product', "rebate");
        $this->prod_attribs['msds'] = $installer->getAttribute('catalog_product', "msds");
    }
    
    public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}
    
	public function dbConnectNormal($dbArray)
	{
	   	$connect=mysql_connect($dbArray['host'],$dbArray['username'],$dbArray['password']);
		if (!$connect) {
			die('Could not connect: ' . mysql_error());
		}
		$db_selected = mysql_select_db($dbArray['dbname'],$connect);
		if (!$db_selected) {
			die ('Database Not Connected : ' . mysql_error());
		}
		mysql_set_charset("utf8",$connect);
		mysql_query($dbArray['initStatements'],$connect);
		$this->connect = $connect;
	}
	public function Select($sql)
	{
		try {
			$res = mysql_query($sql);

			while($row = mysql_fetch_assoc($res))
			{
				$result[] = $row;
			}
			mysql_free_result($res);
			return $result;
		}catch (Exception $e) {
			$this->logMsg[] = "Query Fail:".$sql. $e->getMessage();
		}
	}
	public function Query($sqlMultiple)
	{
	 	try {
	 	 	foreach (explode(";", $sqlMultiple) as $sql) {
	 	 	    if($sql !=''){
	 	 	       if(!mysql_query($sql)) {
    				    $this->logMsg[] = mysql_error();
    				};
                }
            }
		}catch (Exception $e) {
			$this->logMsg[] = "Query Fail:".$sql. $e->getMessage().mysql_error();
		}
	}
	public function writeLog($sku)
	{
		$message = '';
		if(count($this->logMsg) > 0) {
			if(is_array($this->logMsg)) {
				foreach ($this->logMsg as $msg) {
					$message .= "No.#: ".($this->start+1).": ".$msg;
				}
				//Mage::log($message, 7, $this->logFile);
			}
		}
		$this->Query("UPDATE ".TEMP_TABLE." SET status='1' WHERE sku = '".$sku."'");
		$this->logMsg = array();
	}
	public function list_all_files($conn_id, $path){
	    
		$buff = ftp_nlist($conn_id, $path);
        ftp_pasv($conn_id,true);
		$final =  preg_grep('/.zip$/i',$buff);
       	$i =0;
       	$fileSuffix=$this->getConfigVal('file_suffix');
		
		$zipArray = array();
		foreach ($final as $val) {
			if(strstr($val,$fileSuffix)) {
				$ar = explode("/",$val);
				$zipArray[] = end($ar);
			}
		}
		return $zipArray;
	}

	public function downloadFiles()
	{
	    $conn_id = ftp_connect($this->getConfigVal('price_file_url'));
        $login_result = ftp_login($conn_id, $this->getConfigVal('user') , $this->getConfigVal('password') );
        $Zips = $this->list_all_files($conn_id, $this->getConfigVal('price_file_ftp_path'));
       	foreach($Zips as $Zip) {
			if (ftp_get($conn_id, Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER).$Zip,
			$this->getConfigVal('price_file_ftp_path')."/".$Zip, FTP_BINARY)) {
			     if(PHP_OS == 'WINNT'){
			         $this->unzip1(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER).$Zip); 
    			    }else{
    			      $this->unzip(Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER).$Zip);
    			    }
                Mage::log($Zip ." Downloaded Successfully ! ", 7, $this->logFile);
				
			}else {
					Mage::log($Zip ." Downloading Problem ! ", 7, $this->logFile);
			}
		}
		ftp_close($conn_id);
        
	}
    
    public function unzip($src_file)
	{
	   
       	//$file_name = substr($src_file,0,-4).".TXT";
        $file_name=Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER).$this->getConfigVal('ftp_file');
		exec('cd '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER),$echoed);
		exec('unzip -o  ' . $src_file. ' -d '.Maven_ManageCatalogSpr_Model_Setting::getImportPath(Maven_ManageCatalogSpr_Model_Setting::ADDTIONALDATA_FOLDER),$echoed);
        
        if(file_exists($file_name)){
       	  $this->fileArray[] = $file_name;
	    }else{
	      $this->fileArray[] = " ";
	    }
	}
    
    public function setFile($file_name)
	{
		$this->fileArray[] = $file_name;
	}
	
    	/**
	 * Unzip the source_file in the destination dir
	 * @Todo work only for the windows OS
	 * @param   string      The path to the ZIP-file.
	 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
	 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
	 * @param   boolean     Overwrite existing files (true) or not (false)
	 *
	 * @return  boolean     Succesful or not
	 */
	public function unzip1($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
	{
		if(function_exists("zip_open"))
		{
			if(!is_resource(zip_open($src_file)))
			{
				$src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
			}

			if (is_resource($zip = zip_open($src_file)))
			{
				$splitter = ($create_zip_name_dir === true) ? "." : "/";
				if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
					
				// Create the directories to the destination dir if they don't already exist
				$this->create_dirs($dest_dir);

				// For every file in the zip-packet
				while ($zip_entry = zip_read($zip))
				{
					// Now we're going to create the directories in the destination directories

					// If the file is not in the root dir
					$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
					if ($pos_last_slash !== false)
					{
						// Create the directory where the zip-entry should be saved (with a "/" at the end)
						$this->create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
					}

					// Open the entry
					if (zip_entry_open($zip,$zip_entry,"r"))
					{
							
						// The name of the file to save on the disk
						$file_name = $dest_dir.zip_entry_name($zip_entry);
						$this->setFile($file_name);
						
						// Check if the files should be overwritten or not
						if ($overwrite === true || $overwrite === false && !is_file($file_name))
						{
							// Get the content of the zip entry
							$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

							if(!is_dir($file_name))
							file_put_contents($file_name, $fstream );
							// Set the rights
							if(file_exists($file_name))
							{
								chmod($file_name, 0777);
								//echo "<br />\n<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
							}
							else
							{
								$this->writeLog("<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
								die( "<br />\n<span style=\"color:red;\">file not found: </span>".$file_name."<br />");
							}
						}
							
						// Close the entry
						zip_entry_close($zip_entry);
					}
				}
				// Close the zip-file
				zip_close($zip);
			}
			else
			{
				$this->writeLog("No Zip Archive Found");
				die("No Zip Archive Found.");
				return false;
			}

			return true;
		}
		else
		{
			if(version_compare(phpversion(), "5.2.0", "<"))
			$infoVersion="(use PHP 5.2.0 or later)";
			$this->writeLog("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
			die("<br />\nYou need to install/enable the php_zip.dll extension $infoVersion");
		}
	}
    
    	/**
	 * @Todo work only for the windows OS
	 * @param unknown_type $path
	 * @return unknown_type
	 */
	public function create_dirs($path)
	{
		if (!is_dir($path))
		{
			$directory_path = "";
			$directories = explode("/",$path);
			array_pop($directories);

			foreach($directories as $directory)
			{
				$directory_path .= $directory."/";
				if (!is_dir($directory_path))
				{
					mkdir($directory_path);
					chmod($directory_path, 0777);
				}
			}
		}
	}
    
    public function getFileattribute()
    {
        if($this->file){
        try{
            if($this->file =='MSDS4QTR.txt'){
                    $attribute=$this->prod_attribs['msds'];
            }else if($this->file =='DEMOS4QTR.txt'){
                $attribute=$this->prod_attribs['tour'];
            }else if($this->file =='REBATES4QTR.txt'){
                $attribute=$this->prod_attribs['rebate'];
            }else{
                $attribute=$this->prod_attribs['brochure'];
            }
            return $attribute;
       }catch (Exception $e) {
			Mage::log($e->getMessage(), 7, $this->logFile);
	   } 
      }else{
         return $attribute = "";
      } 
    }
    
    public function prepareData()
    {
        $attribute=$this->getFileattribute();
        if(isset($attribute['attribute_id'])){
            $this->start = 0;
    		while ($this->start < $this->total) {
    			$products = $this->Select($this->sql. " LIMIT 0 , ".$this->_batchLimit);
                foreach($products as $product) {
                    $sqlInsert="INSERT INTO catalog_product_entity_".$attribute['backend_type']."
                        (`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`)
                        VALUES
                        (".$attribute['entity_type_id'].",".$attribute['attribute_id'].",".$this->_store.",".$product['product_id'].",'".$product['content']."');";
                    $this->Query($sqlInsert);  		
    				$this->writeLog($product['sku']);
    				$this->start++;
    			} 
    		  }
        }else{
            Mage::log("attribute deos not exists ! ", 7, $this->logFile);          
         }
     }
    
    public function processData($filePath)
    {
        try {
            $this->file="";
            $this->sql="";
            $this->total="";
            $this->file=basename($filePath);
            if($filePath!='' &&  file_exists($filePath)) {
                $file = str_replace("\\","\\\\",$filePath);
                $sql=   "TRUNCATE TABLE `".TEMP_TABLE."`;";
                $sql.="LOAD DATA INFILE '".$file."'
                      REPLACE INTO TABLE `".TEMP_TABLE."`
                      FIELDS TERMINATED BY '\\t'
                      LINES TERMINATED BY '\\r\\n'
                      (`sku`,`content`,@dummy,@dummy,@dummy);";
                $sql.="UPDATE `".TEMP_TABLE."` as `ts`,`catalog_product_entity` AS `e`
                      SET `ts`.`product_id` = `e`.`entity_id`
				      WHERE `ts`.`sku` = `e`.`sku`;";
                $sql.= "DELETE FROM `".TEMP_TABLE."` WHERE `product_id` IS NULL;";       
                $this->Query($sql);
                $from = " FROM `".TEMP_TABLE."` WHERE status='0' ORDER BY id ASC ";
        		$this->sql = "SELECT * ".$from;
        		$res = $this->select("SELECT count(*) AS total ". $from);
        		$this->total = $res[0]['total'];
                $this->prepareData();
                Mage::log($filePath." Stored Successfully ! ", 7, $this->logFile);
           	}else {
				Mage::log($filePath." File not exists ! ", 7, $this->logFile);
			}
		}catch (Exception $e) {
			Mage::log($filePath." Stored Failure ! ". $e->getMessage(), 7, $this->logFile);
		}
    }
    public function fileProcess()
	{
	    $files=explode(',',$this->_addtionalFiles);
        if(is_array($this->fileArray))
        {
            foreach ($this->fileArray as $file){
                if(in_array(basename($file),$files)){
                 if(file_exists($file)){
                    $this->processData($file);
                  }else{
                     Mage::log($file." File not exists ! ", 7, $this->logFile);
                  }
                }
            }
        }
	}
    
    public function process()
	{
	    /*$this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\MSDS4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\REBATES4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\SL4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\BROC4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\FF4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\CL4QTR.txt';
        $this->fileArray[] = 'G:\vhosts\flatrox.etilize\public_html\var\import\ADDINFO\4Q10_Full_Catalog\DEMOS4QTR.txt';
        */
        $this->downloadFiles();
        $this->fileProcess();
        $this->closeConnection();
		$this->reIndexAll();
	}
	public function reIndexAll()
    {
	    $indexterPath=Mage::getBaseDir()."/shell/indexer.php";
		if(file_exists($indexterPath)){  
				system("php ".$indexterPath." --reindex catalog_product_attribute,catalog_product_flat");
        }
		Mage::app()->cleanCache();
    }
}
$obj = new updateAdditionalData();
$obj->process();
